package com.vancouver.knows.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.pangu.util.FileUtil;
import com.pangu.util.StringUtil;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.ui.activity.login.LoginActivity;
import com.vancouver.knows.ui.view.ShareDialog;

public class AppUtils {

	public static final String sdfStr = "yyyy-MM-dd";
	public static final String sdfTimeStr = "yyyy-MM-dd'T'HH:mm:ss";
	public static final String eventSdfStr = "E MM月dd,yyyy";
	public static final String timeStr = "yyyy-MM-dd HH:mm:ss";
	private static final String SCHEME_CONTENT = "content";

	public static String getPdg() {
		SimpleDateFormat sdf = new SimpleDateFormat(sdfStr);
		return sdf.format(new Date());
	}

	public static String getPdg(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat(sdfStr);
		return sdf.format(date);
	}

	public static String getEventPdg(String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(sdfStr);
		try {
			sdf.setTimeZone(TimeZone.getTimeZone("UTC-8"));
			Date date = sdf.parse(dateStr);
			return sdf.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return "";
	}

	/**
	 *  * Try to return the absolute file path from the given Uri  *  * @param
	 * context  * @param uri  * @return the file path or null  
	 */
	public static String getRealFilePath(final Context context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	public static String getArrayStr(String[] str) {
		if (str == null || str.length == 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0, size = str.length; i < size; i++) {
			sb.append(str[i]);
			if (i < size - 1) {
				sb.append(",");
			}
		}

		return sb.toString();
	}

	public static String geEventtArrayStr(String[] str) {
		if (str == null || str.length == 0) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0, size = str.length; i < size; i++) {
			sb.append("#");
			sb.append(str[i]);
			if (i < size - 1) {
				sb.append(" ");
			}
		}

		return sb.toString();
	}

	public static void shareContent(final Activity activity, final String title, final String url, final String imgUrl) {
		ShareSDK.initSDK(activity);

		final ShareDialog shareDialog = new ShareDialog(activity);
		shareDialog.setCancelButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				shareDialog.dismiss();

			}
		});
		shareDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
				if (item.get("ItemText").equals(activity.getResources().getString(R.string.wechat))) {
					ShareParams wechat = new ShareParams();
					wechat.setText(title);
					if (StringUtil.isEmptyString(imgUrl)) {
						wechat.setImageData(((BitmapDrawable) activity.getResources().getDrawable(R.mipmap.ic_launcher))
								.getBitmap());
					} else {
						wechat.setImageUrl(imgUrl);
					}

					if (StringUtil.isEmptyString(url)) {
						wechat.setShareType(Platform.SHARE_IMAGE);
					} else {
						wechat.setUrl(url);
						wechat.setShareType(Platform.SHARE_WEBPAGE);
					}

					Platform weixin = ShareSDK.getPlatform(activity, Wechat.NAME);
					weixin.setPlatformActionListener(null);
					weixin.share(wechat);

				} else if (item.get("ItemText").equals(activity.getResources().getString(R.string.wechatmoments))) {
					ShareParams wechatMoments = new ShareParams();
					wechatMoments.setTitle(title);
					wechatMoments.setText(title);
					if (StringUtil.isEmptyString(imgUrl)) {
						wechatMoments.setImageData(((BitmapDrawable) activity.getResources().getDrawable(
								R.mipmap.ic_launcher)).getBitmap());
					} else {
						wechatMoments.setImageUrl(imgUrl);
					}
					if (StringUtil.isEmptyString(url)) {
						wechatMoments.setShareType(Platform.SHARE_IMAGE);
					} else {
						wechatMoments.setUrl(url);
						wechatMoments.setShareType(Platform.SHARE_WEBPAGE);
					}

					Platform weixin = ShareSDK.getPlatform(activity, WechatMoments.NAME);
					weixin.setPlatformActionListener(null);
					weixin.share(wechatMoments);

				} else if (item.get("ItemText").equals(activity.getResources().getString(R.string.sinaweibo))) {
					if (!checkApkExist(activity, "com.sina.weibo")
							&& !checkApkExist(activity, "com.sina.weibo.nightdream")) {
						return;
					}

					SinaWeibo.ShareParams sp = new SinaWeibo.ShareParams();
					String weiboText = title;
					if(!StringUtil.isEmptyString(url)){
						weiboText = "【" + title + "】" + activity.getResources().getString(R.string.share_weibo_content,url);
					}
					sp.setText(weiboText);

					sp.setShareType(Platform.SHARE_WEBPAGE);
					if (StringUtil.isEmptyString(imgUrl)) {
						sp.setImageData(((BitmapDrawable) activity.getResources().getDrawable(R.mipmap.ic_launcher))
								.getBitmap());
					} else {
						sp.setImageUrl(imgUrl);
					}
					Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
					weibo.setPlatformActionListener(new PlatformActionListener() {

						@Override
						public void onError(Platform arg0, int arg1, Throwable arg2) {
						}

						@Override
						public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
							Toast.makeText(activity, R.string.share_success, 200).show();
						}

						@Override
						public void onCancel(Platform arg0, int arg1) {

						}
					}); // 设置分享事件回调
					// 执行图文分享
					weibo.share(sp);
				}
				shareDialog.dismiss();

			}
		});

	}

	public static String getBitmapFilePath(String imgUrl) {
		if (StringUtil.isEmptyString(imgUrl)) {
			return "";
		} else {
			return FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.SHARE_IMAGE_DIR + imgUrl.hashCode()
					+ ".jpg";
		}
	}

	public static void showBrower(Activity activity, String url) {
		if (StringUtil.isEmptyString(url)) {
			return;
		}

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(url));
		activity.startActivity(intent);
	}

	public static int getWindowWidth(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		return display.getWidth();
	}

	public static SpannableStringBuilder replaceColor(String str, String index, int color) {
		SpannableStringBuilder style = new SpannableStringBuilder(str);
		int start = str.indexOf(index);
		if (start == -1) {
			return style;
		}
		style.setSpan(new ForegroundColorSpan(color), start, start + index.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

		return style;
	}

	public static String getDateStr(Context context, String time) {
		String timeStr = "";
		SimpleDateFormat sdf = new SimpleDateFormat(sdfTimeStr);
		sdf.setTimeZone(TimeZone.getTimeZone("UTC-8"));
		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (date == null) {
			return "";
		}

		long dateLong = date.getTime();
		long currentLong = new Date().getTime();
		long off = (currentLong - dateLong) / 1000;
		if (off / 60 <= 1) {
			return "刚刚";
		} else if (off / 3600 < 1) {
			timeStr = context.getResources().getString(R.string.minute_before, (int) off / 60);
		} else if (off / 86400 < 1) {
			timeStr = context.getResources().getString(R.string.house_before, (int) off / 3600);
		}else if(off/(86400*7)<1){
			timeStr = context.getResources().getString(R.string.date_before, (int) off / 86400);
		}else if(off/(86400*30)<1){
			timeStr = context.getResources().getString(R.string.week_before, (int) off / (86400*7));
		}else if(off/(86400*365)<1){
			timeStr = context.getResources().getString(R.string.month_before, (int) off / (86400*30));
		}
		else {
			timeStr = context.getResources().getString(R.string.year_before, (int) off / (86400*365));
		}

		return timeStr;
	}

	public static boolean getLoginStatus(Context activity) {
		BSharedPrefManager sharePrefManager = ((MainApplication) activity.getApplicationContext())
				.getSharedPrefManager();
		if (sharePrefManager.getUserId() != null) {
			return true;
		} else {
			activity.startActivity(new Intent(activity, LoginActivity.class));
			return false;
		}
	}

	public static String createFile(Activity activity, Uri uri, String path) {
		if (SCHEME_CONTENT.equals(uri.getScheme())) {
			FileOutputStream outStream = null;
			BufferedInputStream bis = null;
			try {
				outStream = new FileOutputStream(path);
				bis = new BufferedInputStream(activity.getContentResolver().openInputStream(uri));
				byte[] buf = new byte[1024];
				int size = 0;
				while ((size = bis.read(buf)) != -1) {
					outStream.write(buf, 0, size);
				}

				return path;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (outStream != null) {
					try {
						outStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}

	public static boolean clearImageDiskCache(Context context) {
		File cache = new File(context.getApplicationContext().getCacheDir(), "picasso-cache");
		if (cache.exists() && cache.isDirectory()) {
			return deleteDir(cache);
		}
		return false;
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}

	public static boolean isDoNotDisturb() {
		long time = System.currentTimeMillis();
		final Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(time);
		int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
		if (mHour >= 23 || mHour < 8) {
			return true;
		}

		return false;
	}

	public static SpannableStringBuilder createDistanceStr(long distance, int color) {
		String dis;
		String disStr;
		if ((distance / 1000) >= 1) {
			DecimalFormat decimalFormat = new DecimalFormat("0.0");
			double distan = distance / 1000d;
			dis = decimalFormat.format(distan);
			disStr = "距您" + dis + "公里";
		} else {
			dis = distance + "";
			disStr = "距您" + dis + "米";
		}

		return replaceColor(disStr, dis, color);
	}

	public static SpannableStringBuilder createDistanceStrShort(long distance, int color) {
		String dis;
		String disStr;
		if ((distance / 1000) >= 1) {
			DecimalFormat decimalFormat = new DecimalFormat("0.0");
			double distan = distance / 1000d;
			dis = decimalFormat.format(distan);
			disStr = dis + "公里";
		} else {
			dis = distance + "";
			disStr = dis + "米";
		}

		return replaceColor(disStr, dis, color);
	}

	public static boolean isImg(String url) {
		int imgType = url.lastIndexOf(".");
		String imgTypeStr = url.substring(imgType);
		if (imgTypeStr.equals(".jpg") || imgTypeStr.equals(".jpeg") || imgTypeStr.equals(".png")) {
			return true;
		}

		return false;
	}

	public static boolean checkApkExist(Context context, String packageName) {
		if (packageName == null || "".equals(packageName))
			return false;
		try {
			ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
					PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}

	private static boolean isAvilible(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();
		// 获取所有已安装程序的包信息
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
		for (int i = 0; i < pinfo.size(); i++) {
			Log.e("aaa", pinfo.get(i).packageName);
			if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
				return true;
		}
		return false;
	}

	public static boolean isNewVersion(String newVersion, String currentVersion)
	{
		boolean result = false;
		int[] newVersionArray = getArray(newVersion);
		int[] currentVersionArray = getArray(currentVersion);
		int minlength = newVersionArray.length < currentVersionArray.length ? newVersionArray.length : currentVersionArray.length;
		for(int i = 0; i < minlength; i++) {
			if(currentVersionArray[i] < newVersionArray[i])
			{
				result = true;
				break;
			}
		}
		if(!result && newVersionArray.length > currentVersionArray.length) {
			result = true;
		}

		return result;
	}

	public  static int[] getArray(String version)
	{
		try
		{
			String[] versionArray = version.split("\\.");
			int[] result = new int[versionArray.length];
			for(int i = 0; i < versionArray.length; i++) {
				result[i] = Integer.parseInt(versionArray[i]);
			}
			return result;
		}catch (Exception e)
		{
			e.printStackTrace();
			return new int[0];
		}

	}

	public static String getAppVer(Context context){
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static boolean hasInstallGGP(Context context){
		PackageManager pManager = context.getPackageManager();
		try {
			pManager.getApplicationIcon("com.android.vending");
			return true;
		} catch (NameNotFoundException e) {
		}
		return false;
	}

	public static String getUserId(BusinessModule bModule){
		String userId = "";
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		if (userInfo != null) {
			userId = userInfo.getUserID();
		}
		return userId;
	}

	public static int dip2px(Context context, float dipValue){
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int)(dipValue * scale + 0.5f);
	}

	/**
	 * 图片转成string
	 *
	 * @param bitmap
	 * @return
	 */
	public static String convertIconToString(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		byte[] appicon = baos.toByteArray();// 转为byte数组

		String st = Base64.encodeToString(appicon, Base64.DEFAULT);

		return st;
	}

	/**
	 * string转成bitmap
	 *
	 * @param st
	 */
	public static Bitmap convertStringToIcon(String st) {
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(st, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);

			return bitmap;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 黄页详情页中，生成绘制不同的二维码
	 */
	public static String createQrImage(Activity activity) {
		QRCodeWriter writer = new QRCodeWriter();
		try {
			String promoCode =  ((MainApplication) activity.getApplication()).getSharedPrefManager().getUserIdHash();
			if (!StringUtil.isEmptyString(promoCode)) {
				//String url = "https://vancoolver.ca/admin/record_deals.php?text=" + promoCode;
				BitMatrix bitMatrix = writer.encode(promoCode, BarcodeFormat.QR_CODE, 240, 240);
				int width = bitMatrix.getWidth();
				int height = bitMatrix.getHeight();
				Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
				for (int x = 0; x < width; x++) {
					for (int y = 0; y < height; y++) {
						bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
					}
				}

				return AppUtils.convertIconToString(bitmap);
				//qrImageView.setImageBitmap(bitmap);
			}else {

				return null;
			}

		} catch (WriterException e) {
			e.printStackTrace();
		}

		return null;

	}

}
